<template>
    <div class="seller-apply-container">
        <h2>申请成为卖家</h2>

        <div class="seller-apply-card">
            <div v-if="loading" class="loading-wrapper">
                <el-skeleton :rows="4" animated />
            </div>

            <div v-else>
                <!-- 申请状态展示 -->
                <div v-if="application" class="application-status">
                    <div class="status-card">
                        <div class="status-title">您的卖家申请状态</div>
                        <div class="status-info">
                            <div class="status-row">
                                <span class="label">申请人:</span>
                                <span>{{ application.name }}</span>
                            </div>
                            <div class="status-row">
                                <span class="label">身份证号:</span>
                                <span>{{ maskIdNumber(application.idNumber) }}</span>
                            </div>
                            <div class="status-row">
                                <span class="label">申请状态:</span>
                                <span>
                                    <el-tag :type="getStatusTag(application.status)">
                                        {{ getStatusText(application.status) }}
                                    </el-tag>
                                </span>
                            </div>
                        </div>
                    </div>

                    <!-- 已通过 -->
                    <div v-if="application.status === 1" class="status-actions">
                        <p class="success-tip">恭喜！您的卖家申请已通过审核，现在可以发布拍卖品了。</p>
                        <el-button type="primary" @click="$router.push('/user/seller')">进入卖家中心</el-button>
                    </div>

                    <!-- 审核中 -->
                    <div v-else-if="application.status === 0" class="status-actions">
                        <p class="waiting-tip">您的申请正在审核中，请耐心等待...</p>
                        <el-button @click="refreshApplicationStatus">刷新状态</el-button>
                    </div>

                    <!-- 被拒绝 -->
                    <div v-else-if="application.status === 2" class="status-actions">
                        <p class="rejected-tip">
                            很遗憾，您的申请未通过审核。可以重新提交申请或联系客服了解更多信息。
                        </p>
                        <el-button type="primary" @click="resetApplication">重新申请</el-button>
                    </div>
                </div>

                <!-- 申请表单 -->
                <div v-else class="application-form">
                    <p class="form-intro">
                        成为卖家可以发布您自己的拍卖品。请填写以下信息完成申请。
                    </p>

                    <el-form ref="applicationFormRef" :model="applicationForm" :rules="rules" label-width="120px"
                        class="apply-form">
                        <el-form-item label="真实姓名" prop="name">
                            <el-input v-model="applicationForm.name" placeholder="请输入您的真实姓名"></el-input>
                        </el-form-item>

                        <el-form-item label="身份证号" prop="idNumber">
                            <el-input v-model="applicationForm.idNumber" placeholder="请输入您的身份证号码"
                                maxlength="18"></el-input>
                        </el-form-item>

                        <el-form-item label="营业执照" prop="businessLicense">
                            <el-upload class="license-uploader" :http-request="handleUpload"
                                :before-upload="beforeUpload" :show-file-list="false" list-type="picture-card">
                                <img v-if="applicationForm.businessLicense" :src="applicationForm.businessLicense"
                                    class="license-image" />
                                <el-icon v-else class="license-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>
                            <template #tip>
                                <div class="el-upload__tip">
                                    请上传营业执照照片，支持jpg、png格式，最大2MB
                                </div>
                            </template>
                        </el-form-item>

                        <el-form-item class="form-actions">
                            <el-button type="primary" @click="submitApplication" :loading="submitting">
                                提交申请
                            </el-button>
                            <el-button @click="$router.push('/user')">取消</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'
import { getApplicationStatus, applySeller, uploadImage } from '@/api/seller'

const userStore = useUserStore()
const router = useRouter()

const loading = ref(true)
const submitting = ref(false)
const application = ref(null)
const applicationFormRef = ref(null)

const applicationForm = reactive({
    name: '',
    idNumber: '',
    businessLicense: ''
})

const rules = {
    name: [
        { required: true, message: '请输入您的真实姓名', trigger: 'blur' },
        { min: 2, max: 10, message: '姓名长度应为2-10个字符', trigger: 'blur' }
    ],
    idNumber: [
        { required: true, message: '请输入您的身份证号码', trigger: 'blur' },
        { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码', trigger: 'blur' }
    ]
}

// 查询卖家申请状态
const fetchApplicationStatus = async () => {
    loading.value = true
    try {
        const res = await getApplicationStatus()

        if (res && res.code === 1) {
            application.value = res.data

            // 如果已经是卖家，更新store中的卖家状态
            if (application.value && application.value.status === 1) {
                userStore.updateSellerStatus(1)
            }
        } else {
            application.value = null
        }
    } catch (error) {
        console.error('获取申请状态失败:', error)
        ElMessage.error('获取申请状态失败，请稍后再试')
        application.value = null
    } finally {
        loading.value = false
    }
}

// 刷新申请状态
const refreshApplicationStatus = () => {
    fetchApplicationStatus()
    ElMessage.success('状态已刷新')
}

// 重新申请
const resetApplication = () => {
    application.value = null
}

// 提交卖家申请
const submitApplication = () => {
    applicationFormRef.value.validate(async (valid) => {
        if (!valid) return

        submitting.value = true
        try {
            const res = await applySeller(applicationForm)

            if (res && res.code === 1) {
                ElMessage.success('申请提交成功，请等待审核')
                // 等待一小段时间后再获取状态，确保后端数据已更新
                setTimeout(() => {
                    fetchApplicationStatus()
                }, 1000)
            } else {
                ElMessage.error(res?.msg || '申请提交失败')
            }
        } catch (error) {
            console.error('提交申请失败:', error)
            ElMessage.error('提交申请失败，请稍后再试')
        } finally {
            submitting.value = false
        }
    })
}

// 处理文件上传
const handleUpload = async ({ file }) => {
    try {
        const res = await uploadImage(file)
        if (res) {
            applicationForm.businessLicense = res
            ElMessage.success('营业执照上传成功')
        } else {
            ElMessage.error(res?.msg || '上传失败')
        }
    } catch (error) {
        console.error('上传营业执照失败:', error)
        ElMessage.error('上传失败，请重试')
    }
}

// 文件上传前校验
const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isJpgOrPng) {
        ElMessage.error('只能上传JPG/PNG格式的图片!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过2MB!')
        return false
    }
    return true
}

// 获取状态标签类型
const getStatusTag = (status) => {
    const statusMap = {
        0: 'info',    // 待审核
        1: 'success', // 已通过
        2: 'danger'   // 已拒绝
    }
    return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
    const statusMap = {
        0: '审核中',
        1: '已通过',
        2: '已拒绝'
    }
    return statusMap[status] || '未知状态'
}

// 身份证号脱敏处理
const maskIdNumber = (idNumber) => {
    if (!idNumber) return ''
    return idNumber.replace(/(\d{6})(\d+)(\d{4})/, '$1****$3')
}

onMounted(() => {
    fetchApplicationStatus()
})
</script>

<style scoped>
.seller-apply-container {
    padding: 20px;
}

.seller-apply-card {
    background-color: #ffffff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 30px;
    margin-top: 20px;
}

.loading-wrapper {
    padding: 40px 0;
}

.application-status {
    text-align: center;
}

.status-card {
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 30px;
    text-align: left;
}

.status-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #303133;
}

.status-info {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.status-row {
    display: flex;
    align-items: center;
}

.label {
    width: 100px;
    color: #606266;
}

.status-actions {
    margin-top: 30px;
}

.success-tip {
    color: #67c23a;
    font-size: 16px;
    margin-bottom: 20px;
}

.waiting-tip {
    color: #409eff;
    font-size: 16px;
    margin-bottom: 20px;
}

.rejected-tip {
    color: #f56c6c;
    font-size: 16px;
    margin-bottom: 20px;
}

.form-intro {
    margin-bottom: 30px;
    color: #606266;
    font-size: 14px;
}

.apply-form {
    max-width: 600px;
    margin: 0 auto;
}

.license-uploader {
    width: 200px;
    height: 200px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
}

.license-uploader:hover {
    border-color: #409eff;
}

.license-uploader-icon {
    font-size: 28px;
    color: #8c939d;
}

.license-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.form-actions {
    margin-top: 40px;
    text-align: center;
}
</style>